package com.mengniu.commerce.collect.service.impl;


import com.mengniu.commerce.collect.service.WmActService;
import com.mengniu.commerce.collect.third.request.IWeiMengActRequest;
import com.mengniu.commerce.collect.third.response.act.ActDataResponse;
import com.mengniu.commerce.collect.util.RestTemplateUtil;
import com.mengniu.commerce.sync.api.RemoteActService;
import com.mengniu.commerce.sync.api.domain.WeiMengActDataModel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


/**
 * 参数配置 服务层实现
 *
 * @author yz_sm
 */
@Service
public class WmActServiceImpl implements WmActService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private RemoteActService remoteActService;

    @Autowired
    private IWeiMengActRequest weiMengActRequest;

    /***
    * @Description: 行为数据
    * @Param: []
    * @return: void
    * @Author: zfw
    * @Date: 2023/11/30
    * @Date: 10:32
    */
    @Override
    public void getActData() {
        String token = restTemplateUtil.getToken(4001169348805L);
        List<WeiMengActDataModel> list = new ArrayList<>();
        String cursorId ="";
        String successCode ="0";
        // 获取前一天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 格式化为字符串类型的年月日
        String formattedDate = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //第一次请求拿到cursorId(游标ID) 第一次
        ActDataResponse act = weiMengActRequest.getAct(formattedDate,1,cursorId,token);
        if (ObjectUtils.isEmpty(act.getData()) && successCode.equals(act.getCode().getErrcode())){
            //重新赋值给cursorId(第二次)
            cursorId = act.getData().getNextCursorId();
            //获得总数
           int total = act.getData().getTotal();
           int pageSize = 500;
           int pageTotal = (int) Math.ceil(total * 1.0 / pageSize);
           for (int i=0; i<pageTotal;i++){
               //调用微盟接口
               ActDataResponse actNew = weiMengActRequest.getAct(formattedDate,pageSize,cursorId,token);
               cursorId = actNew.getData().getNextCursorId();
               list.addAll(actNew.getData().getList());
           }
        }
        remoteActService.createAct(list,"weimeng-collect-act");
    }
}
